//
//  MBDUserCenter.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/20.
//

import Foundation
import SwiftyJSON
import Dispatch


class MBDUserCenter : NSObject {
    static let shared = MBDUserCenter()
//    var logined : Bool!
        
    // Make sure the class has only one instance
    // Should not init or copy outside
    private override init() {
//        logined = true
    }
    
    override func copy() -> Any {
        return self // SingletonClass.shared
    }
    
    override func mutableCopy() -> Any {
        return self // SingletonClass.shared
    }
    
    var userInfoFetched : Bool {
        
        get  {
            
            let account = MBDAccountInfoModel.current()
            if(nil != account) {
                return  !account!.userId.isBlank
            }
        
            return false
        }
    
    }
    
    var token : String {
        set(tk) {
            if tk.isBlank {
                UserDefaults.standard.removeObject(forKey: "userdefault_token")
                MBDAccountInfoModel.clear()
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UserInfoUpdated"), object: nil)

                return
            }
            UserDefaults.standard.set(tk, forKey: "userdefault_token")
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                // your code here
                if let current = MBDAccountInfoModel.current() {
                    current.update(notify: true)
                } else {
                    MBDAccountInfoModel.fetch()
                }
            }
            
        }
        get  {
            if let tk = UserDefaults.standard.string(forKey: "userdefault_token") {
                return tk
            }
            return ""
        }
    }
    // Optional
    func reset() {
        // Reset all properties to default value
    }
    
}
